4

time.Weekday类型可以做运算,强制转int,会得到偏差数。
默认是 Sunday 开始到 Saturday 算 0,1,2,3,4,5,6

所以只有Monday减去Sunday的时候是正数,特殊处理下就可以了。

package date

import (
    "fmt"
    "time"
)

func WeekDayTest() {
    now := time.Now()

    offset := int(time.Monday - now.Weekday())
    if offset > 0 {
        offset = -6
    }
    
    weekStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, offset)
    fmt.Println(weekStart)
}

boywus
562 声望12 粉丝